package com.leyou.cart.service;

import com.leyou.cart.entity.Cart;
import com.leyou.common.auth.pojo.UserHolder;
import com.leyou.common.constant.LyConstants;
import com.leyou.common.exception.pojo.ExceptionEnum;
import com.leyou.common.exception.pojo.LyException;
import com.leyou.common.utils.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CartService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * <key, <hashKey, value>>
     * @param cart
     */
    public void saveCart(Cart cart) {
        //获取当前用户的id
        Long userId = UserHolder.getUserId();
        //通过用户id获取到当前用户在redis中的购物车数据的key
        String key = LyConstants.CART_PRE+userId;
        //通过key，获取到hash数据<hashKey, value>
        BoundHashOperations<String, String, String> hashCart = redisTemplate.boundHashOps(key);
        //获取到要添加的购物车数据的id，其实就是hashKey
        String hashKey = cart.getSkuId().toString();
        //通过hashKey到hash中判断当前要添加的购物车数据是否已经存在
        if(hashCart.hasKey(hashKey)){
            //如果存在，得到之前的购物车对象
            String oldCart = hashCart.get(hashKey);
            //将新添加的购物车数据量和之前的购物车数据合并
            cart.setNum(cart.getNum()+ JsonUtils.toBean(oldCart, Cart.class).getNum());
        }
        //新添加就可以了。
        hashCart.put(hashKey, JsonUtils.toString(cart));
    }

    public List<Cart> findCarts() {
        //获取当前用户的id
        Long userId = UserHolder.getUserId();
        //通过用户id获取到当前用户在redis中的购物车数据的key
        String key = LyConstants.CART_PRE+userId;
        //判断当前用户是否有购物车数据
        if(!redisTemplate.hasKey(key)){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //通过key获取到hash
        BoundHashOperations<String, String, String> hashCart = redisTemplate.boundHashOps(key);
        //判空
        if(hashCart.size()==0){
            throw new LyException(ExceptionEnum.CARTS_NOT_FOUND);
        }
        //直接获取到所有value的集合
        List<Cart> carts = hashCart.values()
                .stream()
                .map(cart -> JsonUtils.toBean(cart, Cart.class))//将字符串格式的购物车对象转成Cart对象格式
                .collect(Collectors.toList());
        return carts;
    }

    public void addLocalCartsToRedis(List<Cart> carts) {
        carts.forEach(cart -> {
            saveCart(cart);
        });
    }
}
